package com.iweb.servlet;


import com.alibaba.fastjson.JSON;
import com.iweb.constant.CategoryAction;
import com.iweb.constant.MyConstant;
import com.iweb.entity.Category;
import com.iweb.entity.ReturnData;
import com.iweb.service.CategoryService;
import com.iweb.service.impl.CategoryServiceImpl;
import com.iweb.util.Pager;
import com.iweb.util.StringHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author jay
 * @desc 处理后台商品分类业务请求
 */
@WebServlet(name = "categoryServlet", urlPatterns = {"/category.do"})
public class CategoryServlet extends HttpServlet {
    private CategoryService categoryService = new CategoryServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        if (CategoryAction.LISTBYPARENTID.equals(action)) {
            // 显示某分类下的列表
            listByParentId(req, resp);
            return;
        }
        if (CategoryAction.LIST.equals(action)) {
            // 显示列表
            list(req, resp);
            return;
        }
        if (CategoryAction.REMOVE.equals(action)) {
            // 删除
            remove(req, resp);
            return;
        }
        if (CategoryAction.ADD.equals(action)) {
            // 打开新增界面
            req.getRequestDispatcher(MyConstant.JSPPREFIX + "admin/categoryadd.jsp").forward(req, resp);
            return;
        }
        if (CategoryAction.DOADD.equals(action)) {
            // 处理新增表单
            doAdd(req, resp);
            return;
        }
        if (CategoryAction.MODIFY.equals(action)) {
            modify(req, resp);
            return;
        }
        if (CategoryAction.DOMODIFY.equals(action)) {
            doModify(req, resp);
            return;
        }
    }

    /**
     * 显示某分类下的列表  - ajax
     *
     * @param req
     * @param resp
     */
    private void listByParentId(HttpServletRequest req, HttpServletResponse resp) {
        ReturnData returnData = new ReturnData();

        String sid = req.getParameter("parentId");
        if (StringHelper.isEmpty(sid)) {
            returnData.setCode("A0410");
            returnData.setErrorMessage("父分类id不能为空");
        }
        PrintWriter writer = null;
        try {
            resp.setContentType("text/plain;charset=utf-8");
            writer = resp.getWriter();
            // 格式化id
            Integer parentId = Integer.valueOf(sid);
            List<Category> categoryList = this.categoryService.findList(parentId);
            returnData.success(categoryList);
        } catch (Exception e) {
            e.printStackTrace();
            returnData.setCode("A0500");
            returnData.setErrorMessage(e.getMessage());
        } finally {
            if (writer != null) {
                String jsonString = JSON.toJSONString(returnData);
                writer.write(jsonString);
                writer.close();
            }
        }
    }

    /**
     * 处理修改表单
     *
     * @param req
     * @param resp
     */
    private void doModify(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.获取表单数据
        Category category = new Category();
        category.setId(Integer.valueOf(req.getParameter("id")));
        category.setName(req.getParameter("name"));
        category.setType(Integer.valueOf(req.getParameter("type")));
        category.setParentId(Integer.valueOf(req.getParameter("parentId")));
        category.setIconClass(req.getParameter("iconClass"));
        // 2.保存修改类别数据
        try {
            boolean modify = this.categoryService.modify(category);
            if (modify) {
                // 3.进行响应, 保存成功后，跳转到类别列表
                resp.sendRedirect(req.getContextPath() + "/categoryS.do?action=list");
            } else {
                req.getRequestDispatcher(MyConstant.JSPPREFIX + "404.jsp").forward(req, resp);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 设置错误信息
            req.setAttribute("errorMessage", e.getMessage());
            // 跳转到美化后的错误处理界面
            req.getRequestDispatcher(MyConstant.JSPPREFIX + "500.jsp").forward(req, resp);
        }
    }

    /**
     * 打开修改界面
     *
     * @param req
     * @param resp
     */
    private void modify(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 查询数据
        String sid = req.getParameter("id");
        if (sid == null || sid.length() == 0) {
            req.getRequestDispatcher(MyConstant.JSPPREFIX + "404.jsp").forward(req, resp);
            return;
        }
        try {
            Integer id = Integer.parseInt(sid);
            Category category = this.categoryService.findById(id);
            if (category == null) {
                req.getRequestDispatcher(MyConstant.JSPPREFIX + "404.jsp").forward(req, resp);
                return;
            }
            // 保存数据
            req.setAttribute("categoryS", category);
            // 跳转到修改界面
            req.getRequestDispatcher(MyConstant.JSPPREFIX + "admin/categorymodify.jsp").forward(req, resp);

        } catch (Exception e) {
            e.printStackTrace();
            // 设置错误信息
            req.setAttribute("errorMessage", e.getMessage());
            // 跳转到美化后的错误处理界面
            req.getRequestDispatcher(MyConstant.JSPPREFIX + "500.jsp").forward(req, resp);
        }

    }

    /**
     * 处理新增表单
     *
     * @param req
     * @param resp
     */
    private void doAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.获取表单数据
        Category category = new Category();
        category.setName(req.getParameter("name"));
        category.setType(Integer.valueOf(req.getParameter("type")));
        category.setParentId(Integer.valueOf(req.getParameter("parentId")));
//        category.setIconClass(req.getParameter("iconClass"));
        // 2.保存类别数据
        try {
            this.categoryService.add(category);
            // 3.进行响应, 保存成功后，跳转到类别列表
            resp.sendRedirect(req.getContextPath() + "/category.do?action=list");
        } catch (Exception e) {
            e.printStackTrace();
            // 设置错误信息
            req.setAttribute("errorMessage", e.getMessage());
            // 跳转到美化后的错误处理界面
            req.getRequestDispatcher(MyConstant.JSPPREFIX + "500.jsp").forward(req, resp);
        }
    }

    /**
     * 删除类别
     *
     * @param req
     * @param resp
     */
    private void remove(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取要删除的类别id
        String sid = req.getParameter("id");
        if (sid == null || sid.length() == 0) {
            req.getRequestDispatcher(MyConstant.JSPPREFIX + "404.jsp").forward(req, resp);
            return;
        }
        // 执行删除操作
        try {
            Integer id = Integer.parseInt(sid);
            boolean result = this.categoryService.remove(id);
            if (result) {
                // 页面跳转-列表
                resp.sendRedirect(req.getContextPath() + "/category.do?action=list");
            } else {
                req.getRequestDispatcher(MyConstant.JSPPREFIX + "404.jsp").forward(req, resp);
            }

        } catch (Exception e) {
            // 设置错误信息
            req.setAttribute("errorMessage", e.getMessage());
            // 跳转到美化后的错误处理界面
            req.getRequestDispatcher(MyConstant.JSPPREFIX + "500.jsp").forward(req, resp);
        }


    }

    /**
     * 打开类别列表界面,不带搜索
     *
     * @param req
     * @param resp
     */
    private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            Pager<Category> pager = new Pager();
            // 获取前端的分页请求参数
            String sPageIndex = req.getParameter("pageIndex");
            String sPageSize = req.getParameter("pageSize");

            // 设置页码
            if (!StringHelper.isEmpty(sPageIndex)) {
                pager.setPageIndex(Integer.valueOf(sPageIndex));
            }
            // 设置每页显示条数
            if (!StringHelper.isEmpty(sPageSize)) {
                pager.setPageSize(Integer.valueOf(sPageSize));
            }
            // 设置总条数
            pager.setTotalRows(this.categoryService.findTotalRows());

            // 获取分页数据
            List<Category> categoryList = this.categoryService.findPagedList(pager);
            // 把数据保存在pager中
            pager.setList(categoryList);

            // 保存数据
            req.setAttribute("pager", pager);

            // 打开类别列表界面
            req.getRequestDispatcher(MyConstant.JSPPREFIX + "admin/categorylist.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            // 设置错误信息
            req.setAttribute("errorMessage", e.getMessage());
            // 跳转到美化后的错误处理界面
            req.getRequestDispatcher(MyConstant.JSPPREFIX + "500.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
